from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QIcon


# 在QApplication之前先实例化
def read_lines():
    with open('main_pages/todo.txt', 'r', encoding='utf-8') as file:
        file_line = file.readlines()
        file_lines = [f'{num_count}.' + line for num_count, line in enumerate(file_line, start=1)]
    return file_lines, file_line


def write_lines(line):
    with open('main_pages/todo.txt', 'a', encoding='utf-8') as file:
        file.write(line + '\n')


def change_lines(line_number, new_line):
    lines = read_lines()[1]
    lines[line_number - 1] = new_line + '\n'
    with open('main_pages/todo.txt', 'w', encoding='utf-8') as file:
        file.writelines(lines)


def delete_lines(line_number):
    lines = read_lines()[1]
    lines.remove(lines[line_number - 1])
    with open('main_pages/todo.txt', 'w', encoding='utf-8') as file:
        file.writelines(lines)


uiLoader = QUiLoader()


class Stats:

    def __init__(self):
        # 再加载界面
        self.ui = uiLoader.load('main_pages/main.ui')
        self.ui.add.clicked.connect(self.Add)
        self.ui.change.clicked.connect(self.Change)
        self.ui.dele.clicked.connect(self.Delete)
        self.ui.exit.clicked.connect(self.ui.close)
        self.ui.main_text.setPlainText(''.join(read_lines()[0]))

    def Add(self):
        write_lines(self.ui.todo.text())
        self.ui.main_text.setPlainText(''.join(read_lines()[0]))
        self.ui.todo.clear()

    def Change(self):
        change_lines(self.ui.change_number.value(), self.ui.todo_change.text())
        self.ui.main_text.setPlainText(''.join(read_lines()[0]))
        self.ui.todo_change.clear()
        self.ui.change_number.setValue(1)

    def Delete(self):
        delete_lines(self.ui.del_number.value())
        self.ui.main_text.setPlainText(''.join(read_lines()[0]))
        self.ui.del_number.setValue(1)


if __name__ == '__main__':
    app = QApplication([])
    app.setWindowIcon(QIcon('main_pages/logo.jpg'))
    stats = Stats()
    stats.ui.show()
    app.exec()
